import React, { Component } from 'react';
import { HashRouter as Router, Route, Switch } from 'react-router-dom';
import LineChatMain from './components/LineChatMain';
import Logidn from '../common/compont/Logidn';
import ErrorTips from '../common/compont/ErrorTips';
import Error from '../common/compont/Error';
import { Spin, message } from 'antd';
import 'antd/dist/antd.css';
import './components/scss/index.scss';
import { getData, postData1, getQueryVariable } from "../common/js/fetch";
import '@wangeditor/editor/dist/css/style.css'
import { lgAlert } from 'lancoo-web-ui';
import 'lancoo-web-ui/dist/style.css'
import 'lg-select-modal/dist/index.css';
import { w3cwebsocket as W3CWebSocket } from 'websocket';

message.config({
  top: 100,
  duration: 2,
  maxCount: 1,
});

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      start: 0,
      sysId: '460',
      lockerId: '622',
      // token: sessionStorage.getItem('token') || getQueryVariable('lg_tk'),
    };
  }
  alertAInfo2 = () => {
    let alert = lgAlert.show({
      duration: 0,
      content: '您当前的身份没有访问该应用的权限，点击确定返回办公平台',
      tipType: 'info',
      tipSize: 'small',
      tipMouldType: 'A',
      isShowCloseBtn: false,
      showConfirm: false,
      closeText: "知道了",
      onCancel: () => {
        lgAlert.close(alert.index);
        this.openBaseUrl();
      }
    });
  }
  openBaseUrl = () => {
    window.open(sessionStorage.getItem('baseUrl'), '_self');
  }
  componentDidMount() {
    let token = sessionStorage.getItem('token') || getQueryVariable('lg_tk');
    console.log(window.location.href, getQueryVariable('lg_tk'), 'token')
    let isIframe = getQueryVariable('isIframe');
    if (isIframe == '1') {
      sessionStorage.setItem('isIframe', isIframe);
    } else {
      sessionStorage.setItem('isIframe', '2');
    }
    if (getQueryVariable('receiverId') || getQueryVariable('groupId')) {
      sessionStorage.setItem('receiverId', getQueryVariable('receiverId') ? getQueryVariable('receiverId') : '');
      sessionStorage.setItem('receiverName', getQueryVariable('receiverName') ? decodeURIComponent(getQueryVariable('receiverName').replace(/%/g, '%25')) : '');
      sessionStorage.setItem('receiverAvatarPath', getQueryVariable('receiverAvatarPath') ? decodeURIComponent(getQueryVariable('receiverAvatarPath').replace(/%/g, '%25')) : '');
      sessionStorage.setItem('groupId', getQueryVariable('groupId') ? getQueryVariable('groupId') : '');
      sessionStorage.setItem('groupName', getQueryVariable('groupName') ? decodeURIComponent(getQueryVariable('groupName').replace(/%/g, '%25')) : '');
      sessionStorage.setItem('isGroup', getQueryVariable('isGroup') == 1 ? 1 : 2);
      let url = window.location.href.split('?')[0] + "?lg_tk=" + getQueryVariable('lg_tk') + "&lg_ic=" + getQueryVariable('lg_ic') + (isIframe == '1' ? '&isIframe=1' : '');
      window.open(url, '_self');
      return;
    }

    //用户信息获取
    getData('api/commons/school/user/self', { token: token }).then(res => res.json()).then(res => {
      if (res.code == 200 && res.data) {
        // console.log('res.data', res.data);
        let data = res.data;
        sessionStorage.setItem('userInfo', JSON.stringify(data));
        //学校及系统信息获取
        getData('api/commons/school/system/info', {
          schoolId: data.schoolId
        })
          .then(res => res.json())
          .then(res => {
            if (res.code == 200 && res.data) {
              let schoolData = res.data;
              // console.log(res, 'res1', schoolData.baseUrl);
              sessionStorage.setItem('baseUrl', schoolData.baseUrl);
              sessionStorage.setItem('schoolSystemInfo', JSON.stringify(schoolData));
              //验证是否已登录
              if (schoolData) {
                let script = document.createElement("script");
                script.src = schoolData.baseUrl + "/UserMgr/Login/JS/CheckIsOnline2.js";
                script.type = "text/javascript";
                script.onload = function () {
                  // 重复登录检测 
                  window._LgBase_initCheck(schoolData.baseUrl, token, "270");
                }
                document.getElementsByTagName("head")[0].appendChild(script);
              }
              // let url = schoolData.baseUrl + '/UserMgr/PowerMgr/ValidateIdentity'
              // postData1(url, {
              //   IdentityCode: getQueryVariable('lg_ic'),
              //   ModuleID: 222001,
              //   UserID: data.userId
              // })
              //   .then(res => { return res.json() })
              //   .then(res => {
              //     if (res.StatusCode == "200" && res.Data == true) {
                    //锁控校验
                    getData('api/commons/locker/check', {
                      // sysId: schoolData.chatSysId,
                      // lockerId: schoolData.chatLockerId,
                      sysId: this.state.sysId,
                      lockerId: this.state.lockerId,
                      productUseRange: schoolData.productUseRange,
                      schoolId: schoolData.schoolId,
                    }).then(data => {
                      return data.json()
                    }).then(json => {
                      if (json.code == "200" && json.data.result == '1') {
                        console.log('json.data', json.data);
                        this.setState({
                          start: 1
                        })
                      } else {
                        window.open(json.data.lockErrAddr, '_self');
                      }
                    });
                //   } else {
                //     this.alertAInfo2();
                //   }
                // })

            }

          })

      } else {
        let url = window.location.href;
        url = url.split('?');
        if (url.length > 1 && url[1].indexOf('&') > -1) {
          let pram = url[1].split('&');
          url = url[0] + '?';
          pram.map((item) => {
            if (item.indexOf('lg_tk=') === -1) {
              url += item + '&';
            }
          })
          url = url.slice(0, -1);
        } else {
          url = url[0];
        }
        if (url.slice(-2) == '#/') {
          url = url.slice(0, -2);
        }
        url = encodeURIComponent(url);
        sessionStorage.removeItem('token');
        // window.open(sessionStorage.getItem('baseUrl') + '/UserMgr/Login/Login.aspx?lg_sysid=' + '222' + '&lg_preurl=' + url, '_self');
        window.open(sessionStorage.getItem('baseUrl') + '?lg_sysid=' + '222' + '&lg_preurl=' + url, '_self');
        console.log('请重新登录！');
      }
    })
  }

  render() {
    console.log("用户类型：", sessionStorage.getItem('UserType'), "比较结果:", sessionStorage.getItem('UserType') == 0)
    return (
      <div className="App lg-skin-s2">
        {this.state.start === 1 ? <div>
          <div>
            {/* <Search></Search> */}
            <Router>
              {/* exact表示绝对匹配 */}
              {/* 在react-router中每一个Route相当于一个组件 */}
              {/* 在传递参数的时候可以设置成 :参数名? 表示可选参数 */}
              {/* Switch表示只匹配一个符合条件的路由 */}
              <Switch>
                <Route path="/" exact component={LineChatMain} />
                <Route path="/404" component={Logidn} />
                <Route path="/Error" component={Error} />
                <Route path="/ErrorTips" component={ErrorTips} />
              </Switch>
            </Router>
          </div>
        </div> : ''}
        <div className="example" style={{ display: 'none', height: document.documentElement.clientHeight + 'px', lineHeight: document.documentElement.clientHeight + 'px' }}> <Spin size="large" /></div>
      </div>
    );
  }
}
export default App;